package com.example.demo.application;


import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


@SpringBootApplication
@ComponentScan("com.example")
@MapperScan("com.example.demo.dao")
public class LimitApplication {
    public static void main(String[] args) {
        SpringApplication.run(LimitApplication.class, args);
    }

    @Bean
    public org.springframework.web.filter.CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter((CorsConfigurationSource) corsConfigurationSource);

    }

    /**
     * 自定义线程池
     * @return
     */
    @Bean
    public ThreadPoolExecutor getThreadPoolExecutor(){
        //CPU核心数
        int cpuCores = Runtime.getRuntime().availableProcessors();
        //新建线程池
        ThreadPoolExecutor ThreadPoolExecutor = new ThreadPoolExecutor(
                cpuCores * 3,
                cpuCores * 4,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(1000),
                Executors.defaultThreadFactory(),
                new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy()
        );
        return ThreadPoolExecutor;
    }


}
